<?php

namespace addons\wechat\controller;

use addons\wechat\library\Config;
use addons\wechat\model\WechatAutoreply;
use addons\wechat\model\WechatCaptcha;
use addons\wechat\model\WechatContext;
use addons\wechat\model\WechatResponse;
use addons\wechat\model\WechatConfig;
use app\common\model\Subject\Subject;
use app\common\model\Product\Order;
use app\common\model\Product\Product;

use EasyWeChat\Factory;
use addons\wechat\library\Wechat as WechatService;
use addons\wechat\library\Config as ConfigService;
use think\Log;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;

/**
 * 微信接口
 */
class Index extends \think\addons\Controller
{

  public $app = null;

  public function _initialize()
  {
    parent::_initialize();
    $this->app = Factory::officialAccount(Config::load());
  }

  /**
   *
   */
  public function index()
  {
    $this->error("当前插件暂无前台页面");
  }

  /**
   * 微信API对接接口
   */
  public function api()
  {
    $this->app->server->push(function ($message) {
      $wechatService = new WechatService;

      $matches = null;
      $openid = $message['FromUserName'];
      $to_openid = $message['ToUserName'];

      $unknownMessage = WechatConfig::getValue('default.unknown.message');
      $unknownMessage = $unknownMessage ? $unknownMessage : "";

      switch ($message['MsgType']) {
        case 'event': //事件消息
          $event = $message['Event'];
          $eventkey = $message['EventKey'] ? $message['EventKey'] : $message['Event'];
          //验证码消息
          if (in_array($event, ['subscribe', 'SCAN']) && preg_match("/^captcha_([a-zA-Z0-9]+)_([0-9\.]+)/", $eventkey, $matches)) {
            return WechatCaptcha::send($openid, $matches[1], $matches[2]);
          }
          switch ($event) {
            case 'subscribe': //添加关注
              $subscribeMessage = WechatConfig::getValue('default.subscribe.message');
              $subscribeMessage = $subscribeMessage ?: "欢迎来到测试号\n使用帮助\n1、发送城市名称，可搜索天气(广州天气)\n2、发送课程名称，可搜索相关课程(php课程)\n3、发送商城订单号,可搜索订单状态(查订单：2023051111)\n4、发送商品名称，可搜索商品(商品:手机)";
              return $subscribeMessage;
            case 'unsubscribe': //取消关注
              return '';
            case 'LOCATION': //获取地理位置
              return '';
            case 'VIEW': //跳转链接,eventkey为链接
              return '';
            case 'SCAN': //扫码
              return '';
            default:
              break;
          }

          $wechatResponse = WechatResponse::where(["eventkey" => $eventkey, 'status' => 'normal'])->find();
          if ($wechatResponse) {
            $responseContent = (array)json_decode($wechatResponse['content'], true);
            $wechatContext = WechatContext::where(['openid' => $openid])->order('id', 'desc')->find();
            $data = ['eventkey' => $eventkey, 'command' => '', 'refreshtime' => time(), 'openid' => $openid];
            if ($wechatContext) {
              $wechatContext->save($data);
            } else {
              $wechatContext = WechatContext::create($data, true);
            }
            $result = $wechatService->response($this, $openid, '', $responseContent, $wechatContext);
            if ($result) {
              return $result;
            }
          }
          return $unknownMessage;
        case 'text': //文字消息
        case 'image': //图片消息
          // return '图片消息';
        case 'voice': //语音消息
        case 'video': //视频消息
          // return '视频消息';
        case 'location': //坐标消息
        case 'link': //链接消息
        default: //其它消息
          //自动回复处理
          if ($message['MsgType'] == 'text') {
            $autoreply = null;
            $autoreplyList = WechatAutoreply::where('status', 'normal')->cache(true)->order('weigh DESC,id DESC')->select();
            foreach ($autoreplyList as $index => $item) {
              //完全匹配和正则匹配
              if ($item['text'] == $message['Content'] || (in_array(mb_substr($item['text'], 0, 1), ['#', '~', '/']) && preg_match($item['text'], $message['Content'], $matches))) {
                $autoreply = $item;
                break;
              }
            }

            if ($autoreply) {
              $wechatResponse = WechatResponse::where(["eventkey" => $autoreply['eventkey'], 'status' => 'normal'])->find();
              if ($wechatResponse) {
                $responseContent = (array)json_decode($wechatResponse['content'], true);
                $wechatContext = WechatContext::where(['openid' => $openid])->order('id', 'desc')->find();
                $result = $wechatService->response($this, $openid, $message['Content'], $responseContent, $wechatContext, $matches);
                if ($result) {
                  return $result;
                }
              }
            } else {
              return $this->keywords($message['Content']);
            }
          }
          return $unknownMessage;
      }
      return ""; //SUCCESS
    });

    $response = $this->app->server->serve();
    // 将响应输出
    $response->send();
    return;
  }

  /**
   * 登录回调
   */
  public function callback()
  {
  }

  /**
   * 支付回调
   */
  public function notify()
  {
    Log::record(file_get_contents('php://input'), "notify");
    $response = $this->app->handlePaidNotify(function ($message, $fail) {
      // 你的逻辑
      return true;
      // 或者错误消息
      $fail('Order not exists.');
    });

    $response->send();
    return;
  }

  /**
   * 关键字回复  SP202401161201497638142
   */
  public function keywords($content = null)
  {
    //   $content = 'php课程';        
    //$content = 'SP202401131543405197840';
    //   $content = '柜子商品';

    // 天气正则匹配
    preg_match("/^(.*)天气$/", $content, $res);

    $city = $res[1] ?? '';

    if ($city) {

      // 获取城市天气的缓存内容
      $citycontent = cache($city);

      if ($citycontent) {
        return   $citycontent;
      }

      // 天气Api
      $weatherapi = "http://apis.juhe.cn/simpleWeather/query?city=$city&key=9ab6176129dbb280b54721e4da1a1e78";

      $result = file_get_contents($weatherapi);

      $result = json_decode($result, true);

      // 根据粗错误码显示错误信息
      switch ($result['error_code']) {
        case 10011:
          return new Text('您当前请求过多，请稍后再试');

        case 10012:
          return new Text('当前请求过多，请稍后再试');

        case 10020:
          return new Text('该功能正在维护中');

        case 10021:
          return new Text('该功能停用~');

        case 207302:
          return new Text('查询不到该城市的相关信息');

        case 207301:
          return new Text('错误的查询城市名,请重新查询');

        case 207303:
          return new Text('网络错误，请重试');
      }

      $data = $result['result'];

      $weathercontent = "{$data['city']}天气情况：\n天气情况：{$data['realtime']['info']}\n温度：{$data['realtime']['temperature']}℃\n湿度：{$data['realtime']['humidity']}℃\n风向：{$data['realtime']['direct']}\n风力：{$data['realtime']['power']}\n空气质量指数：{$data['realtime']['aqi']}";

      cache($city, $weathercontent);

      return new Text($weathercontent);
    }

    // 课程匹配  云课堂
    preg_match("/^(.*)课程$/", $content, $class);

    $course = $class[1] ?? '';

    if ($course) {

      $sujbectlist = Subject::where('title', 'like', "%$course%")->select();

      if (!$sujbectlist) {
        return new Text('暂无此课程');
      }

      $data = [];

      $cdn = config('site.url');

      foreach ($sujbectlist as $item) {
        $data[] = new NewsItem([
          'title'       => $item['title'],
          'description' => $item['content_text'],
          'url'         => $cdn . "/home/subject/info.html?subid=" . $item['id'],
          'image'       => $item['thumbs_text'],
        ]);
      }

      return  new News($data);
    }

    // VUE商城订单状态
    preg_match("/^SP.*$/", $content, $resorder);
    $order = $resorder[0] ?? '';

    if ($order) {
      $data = Order::where('code', $content)->find();

      if (!$data) {
        return '暂无订单信息';
      }

      $express_text = $data['express_text'] ?? '暂无快递公司';
      $expresscode = $data['expresscode'] ?? '暂无快递单号';

      $orderstr = "商城订单：\n单号: {$data['code']}\n订单状态: {$data['status_text']}\n快递公司: $express_text\n快递单号: $expresscode\n订单金额: {$data['amount']}";

      //   var_dump($orderstr);
      //   exit;

      return $orderstr;
    }



    // 商品   
    preg_match("/^(.*)商品$/", $content, $class);

    $commodity = $class[1] ?? '';

    if ($commodity) {

      $sujbectlist = Product::where('name', 'like', "%$commodity%")->select();

      if (!$sujbectlist) {
        return new Text('该商品不存在');
      }

      $data = [];

      foreach ($sujbectlist as $item) {
        $data[] = new NewsItem([
          'title'       => $item['name'],
          'description' => $item['content'],
          'url'         =>  "http://gwsc.gjjun.top/#/product/product/info?proid=" . $item['id'],
          'image'       => $item['thumbs_text'],
        ]);
      }
      //  var_dump('----------',$data);exit;

      return  new News($data);
    }
  }
}
